<template> 
  <el-upload
          :ref="ref"
          action=""
          :on-change="handleChange"
          :show-file-list="false"
          :limit="limitUpload"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
          :auto-upload="false">
    <el-button type="info">选择文件</el-button>
    <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文 件</div>
  </el-upload>

</template>
<script>
  // npm install xlsx
  const XLSX = require('xlsx');
  // npm install --save moment
  const moment = require('moment');


  export default {
    name: 'upload-excel',
    props: {
      value: {
        type: Array
      },
      columnList: {
        type: Object,
        default: {},
      }
    },
    data() {
      return {
        ref: "upload" + new Date().getTime(),
        limitUpload: 1,
        tableData: [],
      }
    },
    methods: {
      handleChange(file, fileList) {
        this.fileTemp = file.raw;
        if (this.fileTemp) {
          if ((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (this.fileTemp.type == 'application/vnd.ms-excel')) {
            this.readFile(this.fileTemp)
          } else {
            this.$message({
              type: 'warning',
              message: '附件格式错误，请删除后重新上传！'
            })
          }
        } else {
          this.$message({
            type: 'warning',
            message: '请上传附件！'
          })
        }
      },
      readFile(file) {
        let _this = this;
        const fileReader = new FileReader();
        fileReader.onload = ev => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              // 以字符编码的方式解析
              type: "binary",
              cellDates: true
            });
            //取第一张表
            const exlname = workbook.SheetNames[0];
            //生成json表格内容
            let exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]);
            //封装数据
            let tableData = [];

            exl.forEach((item, index) => {
              let errList = [];
              let obj = {};

              for (let c of Object.keys(_this.columnList)) {
                let err = null;
                let value = item[c];
                //排除时间格式
                if (item[c] instanceof Date) {
                  err = `${c}->使用文本格式`;
                }
                obj[_this.columnList[c]] = value;
                if (err) {
                  errList.push(err);
                }
              }

              if (errList.length > 0) {
                obj['hasError'] = true;
                obj['errorMsg'] = errList.join(',');
              }
              tableData.push(obj);
            });
            _this.emitValue(tableData)
          } catch (e) {
            console.log("出错了：：");
            return false;
          }
        };
        fileReader.readAsBinaryString(file);
      },
      emitValue(val) {
        this.$emit("input", val);
        this.clearFiles();
      },
      clearFiles() {
        this.$nextTick(() => {
          this.$refs[this.ref].clearFiles();
        })
      }
    }
  }
</script>
<style>

</style>


